<?php

/**
 * Classe que manipula as requisições feitas ao servidor pela aplicação.
 *
 * @author Bruno E. Fuhr [brunofuhr@yahoo.com.br]
 * @since 26/07/2011
 *
 */

require_once 'FDefaultModel.class.php';
require_once 'FJSONResponse.class.php';
require_once 'FXMLEditor.class.php';

class FHandler
{
    private $class;
    private $model;
    private $controller;
    private $action;
    private $function;
    private $fields;

    public function  __construct($class, $action, $fields)
    {
//        $xml = new FXMLEditor();
//        $path = $xml->getValue('dir.root');
        
        if ( class_exists($class) )
        {
            $this->model = new $class();
            $this->controller = $this->model->getController();
        }
        else
        {
            $this->model = new FDefaultModel();
            $this->controller = $this->model->getController();            
        }
        
        if ( $this->controller instanceof FController )
        {
            $this->controller->setFilters($fields);
        }
        
        if ( strlen($fields['table']) > 0 )
        {            
            $this->controller->setTable($fields['table']);
        }
        $this->action = $action;
        $this->fields = $fields;
        if ( strlen($fields['function']) > 0 )
        {
            $this->function = $fields['function'];
        }

        $this->handle();
    }

    private function handle()
    {
        $jsonResponse = new FJSONResponse();
        
        // Instancia objeto para obter as preferências do sistema.
        //$objPreferencia = new objPreferencia();
        $result = array();

        foreach( $this->fields as $key => $field )
        {
            $key = str_replace(array('_'), '', $key);
            $method = 'set' . ucfirst($key);

            // Se exite um método de setar o valor do campo, o executa passando o valor do campo.
            if ( method_exists($this->controller, $method) )
            {
                $this->controller->$method($field);
            }
        }

        switch( $this->action )
        {
            case "search":
                $data = $this->controller->search();

                $jsonResponse->setSuccess(is_array($data));
                $jsonResponse->setData($data);
                $jsonResponse->setTotal($this->controller->getTotal());
                
                if ( !$data )
                {
                    $jsonResponse->setEmpty(true);
                    $jsonResponse->setMsg($this->controller->getError() ? $this->controller->getError() : 'TODO: PEGAR PREFERENCIA REGISTROS NAO ENCONTRADOS');
                }
                break;

            case "insert":
                $data = $this->controller->insert();

                if ( $data )
                {
                    $jsonResponse->setSuccess(true);
                    $jsonResponse->setId($data);
                    $jsonResponse->setMsg('TODO: PEGAR PREFERENCIA REGISTRO INSERIDO COM SUCESSO');
                }
                else
                {
                    $jsonResponse->setSuccess(false);
                    $jsonResponse->setMsg($this->controller->getError() ? $this->controller->getError() : 'TODO: PEGAR PREFERENCIA REGISTRO NÃO INSERIDO');
                }
                break;

            case "update":
                $data = $this->controller->update();

                $jsonResponse->setSuccess($data);

                if ( $data )
                {
                    $jsonResponse->setMsg('TODO: PEGAR PREFERENCIA REGISTRO ATUALIZADO');
                }
                else
                {
                    $jsonResponse->setMsg($this->controller->getError() ? $this->controller->getError() : 'TODO: PEGAR PREFERENCIA REGISTRO NAO ATUALIZADO');
                }
                break;

            case "delete":
                $data = $this->controller->delete($this->fields['rows']);
                
                $jsonResponse->setSuccess($data);

                if ( $data )
                {
                    $jsonResponse->setMsg('TODO: PEGAR PREFERENCIA REGISTROS EXCLUIDOS');
                }
                else
                {
                    $jsonResponse->setMsg($this->controller->getError() ? $this->controller->getError() : 'TODO: PEGAR PREFERENCIA REGISTROS NAO EXCLUIDOS');
                }
                break;

            case "get":
                    $data = $this->controller->get();
                
                    if ( $data )
                    {
                        $jsonResponse->setSuccess(true);
                        $jsonResponse->setData($data);
                    }
                    else
                    {
                        $jsonResponse->setSuccess(false);
                        $jsonResponse->setData(false);
                        $jsonResponse->setMsg($this->controller->getError() ? $this->controller->getError() : 'TODO: PEGAR PREFERENCIA REGISTRO NÃO ENCONTRADO');
                    }
                break;

            case "list":
                    $data = $this->controller->getList();
                
                    $jsonResponse->setSuccess(is_array($data));
                    $jsonResponse->setData($data);
                    $jsonResponse->setTotal($this->controller->getTotal());

                    if ( !$data )
                    {
                        $jsonResponse->setEmpty(true);
                        $jsonResponse->setMsg($this->controller->getError() ? $this->controller->getError() : 'TODO: PEGAR PREFERENCIA REGISTROS NAO ENCONTRADOS');
                    }
                break;
                
            case "submit":
                                
                    if ( method_exists($this->model, $this->function) )
                    {
                        $jsonResponse = $this->model->{$this->function}($this->fields);
                    }
                    else
                    {
                        $jsonResponse->setSuccess(FALSE);
                        $jsonResponse->setMsg("
                            O método '{$this->function}' não foi implementado.<br>
                            Contate o administrador do sistema.
                        ");
                    }                    
                break;
        }

        $jsonResponse->response();
    }
}

?>
